package com.yun.many.auth.dao.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.yun.many.auth.model.dto.LoginUser;
import com.yun.many.auth.utils.LoginContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
public class CustomMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        LoginUser loginUser = LoginContext.getLoginUser();
        if (Objects.isNull(loginUser)) {
            return;
        }

        this.strictInsertFill(metaObject, "tenantId", loginUser::getTenantId, Long.class);
        this.strictInsertFill(metaObject, "creator", loginUser::getUsername, String.class);
        this.strictInsertFill(metaObject, "modifier", loginUser::getUsername, String.class);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        LoginUser loginUser = LoginContext.getLoginUser();
        if (Objects.isNull(loginUser)) {
            return;
        }

        this.strictInsertFill(metaObject, "tenantId", loginUser::getTenantId, Long.class);
        this.strictInsertFill(metaObject, "modifier", loginUser::getUsername, String.class);
    }
}
